﻿using System;
using System.IO;

using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;

using SharpSvn;

namespace SvnTools.Tasks.VersionManagement
{
	public class SvnGetExternals : Task
	{
		private ITaskItem[] m_externals = null;

		#region Properties

		public string TargetPath { get; set; }

		[Output]
		public ITaskItem[] Externals
		{
			get { return m_externals; }
		}

		public bool Debug { get; set; }

		#endregion

		public override bool Execute()
		{
			if (Debug) { System.Diagnostics.Debugger.Break(); }

			bool success = true;
			string svn_externals = null;

			try
			{

				// If TargetPath isn't set, use the current build directory
				string target_path = TargetPath;
				if (string.IsNullOrEmpty(target_path))
				{
					target_path = Path.GetDirectoryName(BuildEngine.ProjectFileOfTaskNode);
				}

				// Get the svn:externals string value
				using (SvnClient client = new SvnClient())
				{
					if (!client.GetProperty(target_path, "svn:externals", out svn_externals))
					{
						Log.LogWarning("No svn:externals property present in target path: {0}", target_path);
					}
				}

				// parse out the svn:externals entries into MSBuild TaskItems with metadata representing details from the external declaration.
				SvnExternalItem[] ext_items;
				if (SvnExternalItem.TryParse(svn_externals, out ext_items))
				{
					m_externals = new ITaskItem[ext_items.Length];

					for (int i = 0; i < ext_items.Length; i++)
					{
						SvnExternalItem item = ext_items[i];
						TaskItem external = new TaskItem(item.Target);
						external.SetMetadata("Reference", item.Reference);
						external.SetMetadata("PegRevision", item.Revision.ToString());
						external.SetMetadata("OperativeRevision", item.OperationalRevision.ToString());

						m_externals[i] = external;
					}
				}
			}

			catch (Exception e)
			{
				Log.LogErrorFromException(e);
				success = false;
			}

			return success;
		}
	}
}
